package com.jh.paymentchannel.service;

//import static org.hamcrest.CoreMatchers.nullValue;
//import static org.junit.Assert.fail;

import cn.jh.common.tools.Log;
import cn.jh.common.utils.CommonConstants;
import com.alibaba.fastjson.JSON;
import com.google.common.base.Objects;
import com.google.common.collect.Maps;
import com.jh.paymentchannel.business.BranchbankBussiness;
import com.jh.paymentchannel.business.TopupPayChannelBusiness;
import com.jh.paymentchannel.pojo.BankInfoCode;
import com.jh.paymentchannel.pojo.BankNumCode;
import com.jh.paymentchannel.pojo.JFQuickRegister;
import com.jh.paymentchannel.pojo.JFshangaoBindCard;
import com.jh.paymentchannel.util.Util;
import com.jh.paymentchannel.util.jifuquick.AES;
import com.jh.paymentchannel.util.jifuquick.Base64;
import com.jh.paymentchannel.util.jifuquick.HttpClient4Util;
import com.jh.paymentchannel.util.jifuquick.PayGetToken;
import com.jh.paymentchannel.util.jifuquick.TokenConstants;
import net.sf.json.JSONObject;
import org.apache.commons.codec.digest.DigestUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Controller
public class JFshangaopageRequest {

	private static final Logger log = LoggerFactory.getLogger(JFshangaopageRequest.class);

	@Autowired
	private TopupPayChannelBusiness topupPayChannelBusiness;

	@Autowired
	private BranchbankBussiness branchbankBussiness;

	@Autowired
	private Util util;

	@Value("${payment.ipAddress}")
	private String ipAddress;

	/*private static String partnerNo = "TEST001";

	private static String Key = "00000000000000000000000000000000";

	private String JFurl = "http://fast.jfpays.com:19087";*/

	@Value("${jfshangao.partnerNo}")
	private String partnerNo;
	
	@Value("${jfshangao.key}")
	private String Key;
	
	@Value("${jfshangao.url}")
	private String JFurl;
	
	private static final Charset UTF_8 = StandardCharsets.UTF_8;

	private String rateCode = "1001001";

	/**
	 * 进件接口
	 *
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/topup/jfshangao/register")
	public @ResponseBody Object jfShanGaoRegister(HttpServletRequest request,
			@RequestParam(value = "ordercode") String ordercode,
			@RequestParam(value = "provinceOfBank") String provinceOfBank,
			@RequestParam(value = "cityOfBank") String cityOfBank,
			@RequestParam(value = "bankBranchName") String bankBranchName) throws Exception {
		log.info("开始进入进件接口========================");
		Map map = new HashMap();
		Map<String, String> maps = new HashMap<String, String>();
		/** 首先拿到用户的userid, 如果用户已经存在，那么直接拿用户的sdjuserid, 如果用户的默认结算卡已经和当前不一样了。 需要重新注册 **/
		RestTemplate restTemplate = new RestTemplate();
		URI uri = util.getServiceUrl("transactionclear", "error url request!");
		String url = uri.toString() + "/v1.0/transactionclear/payment/query/ordercode";
		MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("order_code", ordercode);
		String result = restTemplate.postForObject(url, requestEntity, String.class);
		log.info("RESULT================" + result);
		JSONObject jsonObject;
		JSONObject resultObj;
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e1) {
			log.error("查询订单信息出错");
			map.put("resp_code", "failed");
			map.put("channel_type", "jfcoin");
			map.put("resp_message", "没有该订单信息");
			return map;
		}

		String userid = resultObj.getString("userid");
		// 费率
		String rate = resultObj.getString("rate");
		// 额外费率
		String extraFee = resultObj.getString("extraFee");
		// 充值卡卡号
		String bankCard = resultObj.getString("bankcard");

		restTemplate = new RestTemplate();
		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/bank/default/userid";
		requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("user_id", userid);
		result = restTemplate.postForObject(url, requestEntity, String.class);

		log.info("RESULT================" + result);
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e1) {
			log.error("查询默认结算卡出错");
			map.put("resp_code", "failed");
			map.put("channel_type", "jfcoin");
			map.put("resp_message", "查询默认结算卡有误");
			return map;
		}
		String respcode = jsonObject.getString("resp_code");
		if (!"000000".equals(respcode)) {

			maps.put("resp_code", "failed");
			maps.put("channel_type", "jfcoin");
			maps.put("resp_message", "没有结算卡");
			return maps;
		}

		// 默认提现卡卡号
		String cardNo = resultObj.getString("cardNo");
		String userName = resultObj.getString("userName");
		/** 身份证号 */
		String idcard = resultObj.getString("idcard");
		String phone = resultObj.getString("phone");
		String bankName = resultObj.getString("bankName");

		restTemplate = new RestTemplate();
		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/query/randomuserid";
		requestEntity = new LinkedMultiValueMap<String, String>();

		String shopUserId;
		try {
			result = restTemplate.postForObject(url, requestEntity, String.class);
			jsonObject = JSONObject.fromObject(result);
			shopUserId = jsonObject.getString("result");
		} catch (Exception e1) {
			log.error("查询用户ID出错！！！！");
			maps.put("resp_code", "failed");
			maps.put("channel_type", "sdj");
			maps.put("resp_message", "没有查询到用户ID");
			return maps;
		}

		log.info("随机获取的userId" + shopUserId);

		restTemplate = new RestTemplate();
		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/shops/query/uid";
		requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("userid", shopUserId);
		result = restTemplate.postForObject(url, requestEntity, String.class);

		log.info("RESULT================" + result);
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e1) {
			log.error("查询商铺信息出错");
			map.put("resp_code", "failed");
			map.put("channel_type", "jfcoin");
			map.put("resp_message", "查询商铺信息有误");
			return map;
		}

		String shopName = resultObj.getString("name");// 商户全称

		restTemplate = new RestTemplate();
		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/bank/default/cardno";
		requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("cardno", bankCard);
		requestEntity.add("type", "0");
		result = restTemplate.postForObject(url, requestEntity, String.class);
		log.info("接口/v1.0/user/bank/default/cardno--RESULT================" + result);
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e) {
			log.error("查询银行卡信息出错");
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", "查询银行卡信息有误");
			return map;
		}
		if (resultObj == null) {
			return null;
		}

		String cardName = resultObj.getString("bankName");

		String cardname = Util.queryBankNameByBranchName(cardName);

		String expiredTime = resultObj.getString("expiredTime");
		String securityCode = resultObj.getString("securityCode");
		String cardtype = resultObj.getString("cardType");

		// =================================

		// 获取令牌
		String token = new PayGetToken().token(Key, TokenConstants.MERCHANT_REGISTERED_TOKEN, ordercode, partnerNo,
				JFurl);

		if ("failed".equals(token)) {
			log.info("获取token出错啦=======");
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", "获取token出错啦,请稍后重试");
			return map;
		}

		// 进件接口的交易代码
		String txnCode = "701001";
		String api = "/rest/api/" + txnCode;

		// 生成一个8位随机数
		String uuid = UUID.randomUUID().toString().replace("-", "");
		String merchantCode = uuid.substring(0, 8);

		String capAmount = "999999";

		String CapAmount = new BigDecimal(capAmount).multiply(new BigDecimal("100")).setScale(0).toString();

		// 将额外费用变成以分为单位
		String ExtraFee = new BigDecimal(extraFee).multiply(new BigDecimal("100")).setScale(0).toString();

		if (bankName.contains("邮")) {
			bankName = "中国邮政储蓄银行";
		} else if (bankName.contains("浦")) {
			bankName = "上海浦东发展银行";
		}

		BankNumCode bankNumCodeByBankName;
		String bankNum = null;
		String bankCode = null;
		try {
			bankNumCodeByBankName = topupPayChannelBusiness.getBankNumCodeByBankName(bankName);
			bankNum = bankNumCodeByBankName.getBankNum();
			bankCode = bankNumCodeByBankName.getBankCode();
		} catch (Exception e) {
			log.info("获取银行代码代号出错啦=======" + e);
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", "暂不支持该银行，请重新更换银行");
			return map;
		}

		BankInfoCode bankInfoCodeByBankName;
		String bankNo = null;
		try {
			bankInfoCodeByBankName = topupPayChannelBusiness.getBankInfoCodeByBankName(bankBranchName);
			bankNo = bankInfoCodeByBankName.getBankNo();
		} catch (Exception e) {
			log.info("获取支行联行号出错啦=======" + e);
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", "暂不支持该支行，请重新更换支行");
			return map;
		}

		JSONObject dto = new JSONObject();
		dto.put("token", token);// token
		dto.put("merchantCode", merchantCode);// 商户号
		dto.put("rateCode", rateCode);// 费率编码
		dto.put("merName", shopName);// 商户名称
		dto.put("merAbbr", shopName);// 商户简称
		dto.put("idCardNo", idcard);// 身份证号
		dto.put("bankAccountNo", cardNo);// 银行卡号
		dto.put("phoneno", phone);// 预留手机号
		dto.put("bankAccountName", userName);// 持卡人姓名
		dto.put("bankAccountType", "PRIVATE");// 银行账户类型
		dto.put("bankName", bankName);// 银行名称
		dto.put("bankSubName", bankBranchName);// 支行名称
		dto.put("bankCode", bankNum);// 银行代码
		dto.put("bankAbbr", bankCode);// 银行代号
		dto.put("bankChannelNo", bankNo);// 支行联行号
		dto.put("bankProvince", provinceOfBank);// 开户行省份
		dto.put("bankCity", cityOfBank);// 开户行市
		dto.put("debitRate", rate);// 借记卡费率
		dto.put("debitCapAmount", CapAmount);// 借记卡封顶
		dto.put("creditRate", rate);// 信用卡费率
		dto.put("creditCapAmount", CapAmount);// 信用卡封顶
		dto.put("withdrawDepositRate", "0");// 提现费率
		dto.put("withdrawDepositSingleFee", ExtraFee);// 单笔提现手续费
		dto.put("isOrgMerchant", "N");// 是否机构商户
		dto.put("head", this.getHead(ordercode, partnerNo, txnCode));

		// ordercode
		String execute = this.execute(Key, JFurl, api, dto.toString(), partnerNo, ordercode);
		log.info(execute);

		String res;
		// 返回状态码
		String respCode;
		String respMsg;
		try {
			com.alibaba.fastjson.JSONObject resJson = JSON.parseObject(execute);
			String sign = resJson.getString("signature");
			res = AES.decode(Base64.decode(resJson.getString("encryptData")), Key.substring(0, 16));

			jsonObject = JSONObject.fromObject(res);
			log.info("jsonObject=======" + jsonObject);
			JSONObject head = jsonObject.getJSONObject("head");
			log.info("head=======" + head);
			respCode = head.getString("respCode");
			log.info("respCode=====" + respCode);
			respMsg = head.getString("respMsg");
			log.info("respMsg======" + respMsg);

		} catch (Exception e) {
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", "亲，进件失败啦！ 请稍后重试");
			return map;
		}

		// 进件成功
		if ("000000".equals(respCode) && "success".equals(respMsg)) {
			// 进件成功返回的商户号
			String merchantUuid = jsonObject.getString("merchantUuid");
			String paltMerchantCode = jsonObject.getString("paltMerchantCode");

			log.info("merchantUuid======" + merchantUuid);
			log.info("paltMerchantCode======" + paltMerchantCode);

			JFQuickRegister jfQuickRegister = new JFQuickRegister();

			jfQuickRegister.setPhone(phone);
			jfQuickRegister.setBankCard(cardNo);
			jfQuickRegister.setIdCard(idcard);
			jfQuickRegister.setMerchantUuid(merchantUuid);
			jfQuickRegister.setMerchantCode(paltMerchantCode);
			jfQuickRegister.setRateCode1(rateCode);
			jfQuickRegister.setDebitRate(rate);
			jfQuickRegister.setWithdrawDepositsingleFee(extraFee);
			jfQuickRegister.setProvince(provinceOfBank);
			jfQuickRegister.setCity(cityOfBank);
			jfQuickRegister.setBankbranchname(bankBranchName);
			try {
				topupPayChannelBusiness.createJFQuickRegister(jfQuickRegister);
			} catch (Exception e) {
				map.put("resp_code", "failed");
				map.put("channel_type", "jfcoin");
				map.put("resp_message", "保存首次进件信息失败");
				return map;
			}

			restTemplate = new RestTemplate();
			uri = util.getServiceUrl("user", "error url request!");
			url = uri.toString() + "/v1.0/user/bank/update/bynewcardno";
			requestEntity = new LinkedMultiValueMap<String, String>();
			requestEntity.add("cardNo", cardNo);
			requestEntity.add("province", provinceOfBank);
			requestEntity.add("city", cityOfBank);
			requestEntity.add("bankBranchName", bankBranchName);
			result = restTemplate.postForObject(url, requestEntity, String.class);

			log.info("RESULT================" + result);
			try {
				jsonObject = JSONObject.fromObject(result);
				resultObj = jsonObject.getJSONObject("result");
			} catch (Exception e) {
				log.error("更新银行信息出错");
				maps.put("resp_code", "failed");
				maps.put("channel_type", "jf");
				maps.put("resp_message", "更新银行信息有误");
				return maps;
			}

			log.info("进件成功================" + res);
			log.info("开始绑卡==============");

			map.put("resp_code", "success");
			map.put("channel_type", "jf");
			map.put("redirect_url",
					ipAddress + "/v1.0/paymentchannel/topup/tojfshangaobindcard?bankName="
							+ URLEncoder.encode(cardname, "UTF-8") + "&cardType=" + URLEncoder.encode(cardtype, "UTF-8")
							+ "&bankCard=" + bankCard + "&ordercode=" + ordercode + "&expiredTime=" + expiredTime
							+ "&securityCode=" + securityCode);
			return map;

		} else {
			log.info("进件失败=====");
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", respMsg);
			return map;
		}

	}

	// 银联绑卡接口
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/topup/jfshangao/pageopencard")
	public @ResponseBody Object pageOpenCard(HttpServletRequest request, HttpServletResponse response, Model model,
			@RequestParam(value = "ordercode") String ordercode,
			@RequestParam(value = "expiredTime", required = false) String expiredTime,
			@RequestParam(value = "securityCode", required = false) String securityCode) throws Exception {

		log.info("开始进入银联绑卡接口========================");
		Map map = new HashMap();
		Map<String, String> maps = new HashMap<String, String>();
		RestTemplate restTemplate = new RestTemplate();
		URI uri = util.getServiceUrl("transactionclear", "error url request!");
		String url = uri.toString() + "/v1.0/transactionclear/payment/query/ordercode";
		MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("order_code", ordercode);
		String result = restTemplate.postForObject(url, requestEntity, String.class);
		log.info("RESULT================" + result);
		JSONObject jsonObject;
		JSONObject resultObj;
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e1) {
			log.error("查询订单信息出错");
			map.put("resp_code", "failed");
			map.put("channel_type", "jfcoin");
			map.put("resp_message", "没有该订单信息");
			return map;
		}

		String userid = resultObj.getString("userid");
		// 充值卡卡号
		String bankCard = resultObj.getString("bankcard");

		restTemplate = new RestTemplate();
		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/bank/default/userid";
		requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("user_id", userid);
		result = restTemplate.postForObject(url, requestEntity, String.class);

		log.info("RESULT================" + result);
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e1) {
			log.error("查询默认结算卡出错");
			map.put("resp_code", "failed");
			map.put("channel_type", "jfcoin");
			map.put("resp_message", "查询默认结算卡有误");
			return map;
		}
		String respcode = jsonObject.getString("resp_code");
		if (!"000000".equals(respcode)) {

			maps.put("resp_code", "failed");
			maps.put("channel_type", "jfcoin");
			maps.put("resp_message", "没有结算卡");
			return maps;
		}

		// 默认提现卡卡号
		String cardNo = resultObj.getString("cardNo");
		String userName = resultObj.getString("userName");
		// 身份证号
		String idcard = resultObj.getString("idcard");
		String phone = resultObj.getString("phone");
		String bankName = resultObj.getString("bankName");

		JFQuickRegister jfQuickRegister = topupPayChannelBusiness.getJFQuickRegisterByPhoneAndBankCard(phone, cardNo);
		String merchantCode = jfQuickRegister.getMerchantCode();

		// 查询信用卡信息
		restTemplate = new RestTemplate();
		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/bank/default/cardno";
		requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("cardno", bankCard);
		requestEntity.add("type", "0");
		result = restTemplate.postForObject(url, requestEntity, String.class);
		log.info("接口/v1.0/user/bank/default/cardno--RESULT================" + result);
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e) {
			log.error("查询银行卡信息出错");
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", "查询银行卡信息有误");
			return map;
		}
		if (resultObj == null) {
			return null;
		}
		// 信用卡卡号
		String cardNo1 = resultObj.getString("cardNo");
		String userName1 = resultObj.getString("userName");
		/** 身份证号 */
		String idcard1 = resultObj.getString("idcard");
		String phone1 = resultObj.getString("phone");
		String bankName1 = resultObj.getString("bankName");

		String returnUrl = ipAddress + "/v1.0/paymentchannel/topup/jfshangao/return_call";
		String notifyUrl = ipAddress + "/v1.0/paymentchannel/topup/jfshangao/notify_call";

		// 获取令牌
		String token = new PayGetToken().token(Key, TokenConstants.OPEN_CARD_PAGE_TOKEN, ordercode, partnerNo, JFurl);

		if ("failed".equals(token)) {
			log.info("获取token出错啦=======");
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", "获取token出错啦,请稍后重试");
			return map;
		}

		// 绑卡接口的交易代码
		String txnCode = "701005";
		String api = "/rest/api/" + txnCode;

		String before = expiredTime.substring(0, 2);
		String after = expiredTime.substring(2, 4);

		BigDecimal big = new BigDecimal(before);
		BigDecimal times = new BigDecimal("12");

		int compareTo = big.compareTo(times);
		// 如果前两位大于12，,代表是年/月的格式
		if (compareTo == 1) {
			expiredTime = before + after;
		} else {
			expiredTime = after + before;
		}

		if (bankName.contains("邮")) {
			bankName = "中国邮政储蓄银行";
		} else if (bankName.contains("浦")) {
			bankName = "上海浦东发展银行";
		}

		BankNumCode bankNumCodeByBankName;
		String bankNum = null;
		String bankCode = null;
		try {
			bankNumCodeByBankName = topupPayChannelBusiness.getBankNumCodeByBankName(bankName);
			bankNum = bankNumCodeByBankName.getBankNum();
			bankCode = bankNumCodeByBankName.getBankCode();
		} catch (Exception e) {
			log.info("获取银行代码代号出错啦=======" + e);
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", "暂不支持该银行，请重新更换银行");
			return map;
		}

		JSONObject dto = new JSONObject();
		dto.put("token", token);// token
		dto.put("smsOrderId", ordercode);// 订单号
		dto.put("platMerchantCode", merchantCode);// 商户号
		dto.put("rateCode", rateCode);// 费率编码
		dto.put("accountName", userName1);// 银行卡户名
		dto.put("cardNo", bankCard);// 银行卡卡号
		dto.put("cardType", "C");// 银行卡类型
		dto.put("certType", "ID");// 证件类型
		dto.put("certNo", idcard1);// 身份证号
		dto.put("phoneno", phone1);// 预留手机号
		dto.put("cvn2", securityCode);// 安全码
		dto.put("expired", expiredTime);// 有效期
		dto.put("pageReturnUrl", returnUrl);// 前台通知地址
		dto.put("offlineNotifyUrl", notifyUrl);// 后台通知地址
		dto.put("bankCode", bankNum);// 银行代码
		dto.put("bankAbbr", bankCode);// 银行代号
		dto.put("head", this.getHead(ordercode, partnerNo, txnCode));

		// ordercode
		String execute = this.execute(Key, JFurl, api, dto.toString(), partnerNo, ordercode);
		log.info(execute);

		String res;
		// 返回状态码
		String respCode;
		String respMsg = null;
		try {
			com.alibaba.fastjson.JSONObject resJson = JSON.parseObject(execute);
			String sign = resJson.getString("signature");
			res = AES.decode(Base64.decode(resJson.getString("encryptData")), Key.substring(0, 16));

			jsonObject = JSONObject.fromObject(res);
			log.info("jsonObject=======" + jsonObject);
			JSONObject head = jsonObject.getJSONObject("head");
			log.info("head=======" + head);
			respCode = head.getString("respCode");
			log.info("respCode=====" + respCode);
			respMsg = head.getString("respMsg");
			log.info("respMsg======" + respMsg);
			String activateStatus = jsonObject.getString("activateStatus");
			log.info("activateStatus======" + activateStatus);

			if ("SUCCESS".equalsIgnoreCase(activateStatus)) {
				log.info("绑卡开通成功======");
				JFshangaoBindCard jfshangaoBindCard = topupPayChannelBusiness.getJFshangaoBindCard(phone1, bankCard);

				if (null == jfshangaoBindCard) {
					JFshangaoBindCard jFshangaoBindCard2 = new JFshangaoBindCard();
					jFshangaoBindCard2.setPhone(phone1);
					jFshangaoBindCard2.setIdCard(idcard1);
					jFshangaoBindCard2.setBankCard(bankCard);

					try {
						topupPayChannelBusiness.createJFshangaoBindCard(jFshangaoBindCard2);
					} catch (Exception e) {
						log.error("保存用户绑卡信息失败======");
						map.put("resp_code", "failed");
						map.put("channel_type", "jf");
						map.put("resp_message", "亲，绑卡失败啦，请稍后重试 ");
						return map;
					}
				} else {
					jfshangaoBindCard.setPhone(phone1);
					jfshangaoBindCard.setIdCard(idcard1);
					jfshangaoBindCard.setBankCard(bankCard);

					try {
						topupPayChannelBusiness.createJFshangaoBindCard(jfshangaoBindCard);
					} catch (Exception e) {
						log.error("保存用户绑卡信息失败======");
						map.put("resp_code", "failed");
						map.put("channel_type", "jf");
						map.put("resp_message", "亲，绑卡失败啦，请稍后重试 ");
						return map;
					}
				}

				map.put("resp_code", "success");
				map.put("channel_type", "jf");
				map.put("redirect_url", ipAddress + "/v1.0/paymentchannel/topup/jfshangaopay?&ordercode=" + ordercode);
				return map;

			} else if ("SIGNING".equalsIgnoreCase(activateStatus) || "INIT".equalsIgnoreCase(activateStatus)) {

				String html = jsonObject.getString("html");
				log.info("html======" + html);

				String substring = html.substring(html.indexOf("<form"), html.indexOf("</form>") + 8);
				log.info("substring============" + substring);

				map.put("resp_code", "signing");
				map.put("channel_type", "jf");
				map.put("pageContent", substring);

				return map;

			} else {
				log.info("绑卡失败=====");
				map.put("resp_code", "failed");
				map.put("channel_type", "jf");
				map.put("resp_message", respMsg);
				return map;
			}

		} catch (Exception e) {
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", "亲，绑卡失败啦，请稍后重试 ");
			return map;
		}

	}

	// 支付短信接口
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/topup/jfshangao/consumesms")
	public @ResponseBody Object consumeSMS(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "ordercode") String ordercode) throws Exception {

		log.info("开始进入支付短信接口========================");
		Map map = new HashMap();
		Map<String, String> maps = new HashMap<String, String>();
		RestTemplate restTemplate = new RestTemplate();
		URI uri = util.getServiceUrl("transactionclear", "error url request!");
		String url = uri.toString() + "/v1.0/transactionclear/payment/query/ordercode";
		MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("order_code", ordercode);
		String result = restTemplate.postForObject(url, requestEntity, String.class);
		log.info("RESULT================" + result);
		JSONObject jsonObject;
		JSONObject resultObj;
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e1) {
			log.error("查询订单信息出错");
			map.put("resp_code", "failed");
			map.put("channel_type", "jfcoin");
			map.put("resp_message", "没有该订单信息");
			return map;
		}

		String amount = resultObj.getString("amount");
		String userid = resultObj.getString("userid");
		// 费率
		String rate = resultObj.getString("rate");
		// 额外费率
		String extraFee = resultObj.getString("extraFee");
		// 充值卡卡号
		String bankCard = resultObj.getString("bankcard");

		restTemplate = new RestTemplate();
		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/bank/default/userid";
		requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("user_id", userid);
		result = restTemplate.postForObject(url, requestEntity, String.class);

		log.info("RESULT================" + result);
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e1) {
			log.error("查询默认结算卡出错");
			map.put("resp_code", "failed");
			map.put("channel_type", "jfcoin");
			map.put("resp_message", "查询默认结算卡有误");
			return map;
		}
		String respcode = jsonObject.getString("resp_code");
		if (!"000000".equals(respcode)) {

			maps.put("resp_code", "failed");
			maps.put("channel_type", "jfcoin");
			maps.put("resp_message", "没有结算卡");
			return maps;
		}

		// 默认提现卡卡号
		String cardNo = resultObj.getString("cardNo");
		String userName = resultObj.getString("userName");
		// 身份证号
		String idcard = resultObj.getString("idcard");
		String phone = resultObj.getString("phone");
		String bankName = resultObj.getString("bankName");

		JFQuickRegister jfQuickRegister = topupPayChannelBusiness.getJFQuickRegisterByPhoneAndBankCard(phone, cardNo);
		String merchantCode = jfQuickRegister.getMerchantCode();

		// 查询信用卡信息
		restTemplate = new RestTemplate();
		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/bank/default/cardno";
		requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("cardno", bankCard);
		requestEntity.add("type", "0");
		result = restTemplate.postForObject(url, requestEntity, String.class);
		log.info("接口/v1.0/user/bank/default/cardno--RESULT================" + result);
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e) {
			log.error("查询银行卡信息出错");
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", "查询银行卡信息有误");
			return map;
		}
		if (resultObj == null) {
			return null;
		}
		// 信用卡卡号
		String cardNo1 = resultObj.getString("cardNo");
		String userName1 = resultObj.getString("userName");
		/** 身份证号 */
		String idcard1 = resultObj.getString("idcard");
		String phone1 = resultObj.getString("phone");
		String bankName1 = resultObj.getString("bankName");

		if (bankName.contains("邮")) {
			bankName = "中国邮政储蓄银行";
		} else if (bankName.contains("浦")) {
			bankName = "上海浦东发展银行";
		}

		BankNumCode bankNumCodeByBankName;
		String bankNum = null;
		String bankCode = null;
		try {
			bankNumCodeByBankName = topupPayChannelBusiness.getBankNumCodeByBankName(bankName);
			bankNum = bankNumCodeByBankName.getBankNum();
			bankCode = bankNumCodeByBankName.getBankCode();
		} catch (Exception e) {
			log.info("获取银行代码代号出错啦=======" + e);
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", "获取银行代码代号出错啦");
			return map;
		}

		// 获取令牌
		String token = new PayGetToken().token(Key, TokenConstants.PAY_SMS_TOKEN, ordercode, partnerNo, JFurl);

		if ("failed".equals(token)) {
			log.info("获取token出错啦=======");
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", "获取token出错啦");
			return map;
		}

		// 支付短信接口的交易代码
		String txnCode = "702003";
		String api = "/rest/api/" + txnCode;

		// 将订单金额变成以分为单位
		String Amount = new BigDecimal(amount).multiply(new BigDecimal("100")).setScale(0).toString();

		JSONObject dto = new JSONObject();
		dto.put("token", token);// token
		dto.put("consumeOrderId", ordercode);// 订单号
		dto.put("platMerchantCode", merchantCode);// 商户号
		dto.put("merchantRateCode", rateCode);// 费率编码
		dto.put("payAmount", Amount);// 支付金额
		dto.put("accountName", userName1);// 银行卡户名
		dto.put("cardNo", bankCard);// 银行卡卡号
		dto.put("cardType", "C");// 银行卡类型
		dto.put("certType", "ID");// 证件类型
		dto.put("certNo", idcard1);// 身份证号
		dto.put("phoneno", phone1);// 预留手机号
		dto.put("bankCode", bankNum);// 银行代码
		dto.put("bankAbbr", bankCode);// 银行代号
		dto.put("head", this.getHead(ordercode, partnerNo, txnCode));

		// ordercode
		String execute = this.execute(Key, JFurl, api, dto.toString(), partnerNo, ordercode);
		log.info(execute);

		String res;
		// 返回状态码
		String respCode;
		String respMsg;
		try {
			com.alibaba.fastjson.JSONObject resJson = JSON.parseObject(execute);
			String sign = resJson.getString("signature");
			res = AES.decode(Base64.decode(resJson.getString("encryptData")), Key.substring(0, 16));

			jsonObject = JSONObject.fromObject(res);
			log.info("jsonObject=======" + jsonObject);
			JSONObject head = jsonObject.getJSONObject("head");
			String payNo = jsonObject.getString("payNo");
			log.info("payNo=======" + payNo);
			respCode = head.getString("respCode");
			log.info("respCode=====" + respCode);
			respMsg = head.getString("respMsg");
			log.info("respMsg======" + respMsg);

			if ("000000".equals(respCode) && "success".equals(respMsg)) {
				map.put("resp_code", "success");
				map.put("channel_type", "jf");
				map.put("pay_no", payNo);

			} else {

				map.put("resp_code", "failed");
				map.put("channel_type", "jf");
				map.put("resp_message", respMsg);
			}

		} catch (Exception e) {
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", "亲，绑卡失败啦！请稍后重试");

		}

		return map;
	}

	// 支付接口
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/topup/jfshangao/consume")
	public @ResponseBody Object cjconsume(HttpServletRequest request,
			@RequestParam(value = "ordercode") String ordercode, @RequestParam(value = "smsCode") String smsCode,
			@RequestParam(value = "payNo") String payNo) throws Exception {

		log.info("开始进入消费支付接口========================");
		Map map = new HashMap();
		Map<String, String> maps = new HashMap<String, String>();
		RestTemplate restTemplate = new RestTemplate();
		URI uri = util.getServiceUrl("transactionclear", "error url request!");
		String url = uri.toString() + "/v1.0/transactionclear/payment/query/ordercode";
		MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("order_code", ordercode);
		String result = restTemplate.postForObject(url, requestEntity, String.class);
		log.info("RESULT================" + result);
		JSONObject jsonObject;
		JSONObject resultObj;
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e1) {
			log.error("查询订单信息出错");
			map.put("resp_code", "failed");
			map.put("channel_type", "jfcoin");
			map.put("resp_message", "没有该订单信息");
			return map;
		}

		String amount = resultObj.getString("amount");
		String userid = resultObj.getString("userid");
		// 费率
		String rate = resultObj.getString("rate");
		// 额外费率
		String extraFee = resultObj.getString("extraFee");
		// 充值卡卡号
		String bankCard = resultObj.getString("bankcard");

		restTemplate = new RestTemplate();
		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/bank/default/userid";
		requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("user_id", userid);
		result = restTemplate.postForObject(url, requestEntity, String.class);

		log.info("RESULT================" + result);
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e1) {
			log.error("查询默认结算卡出错");
			map.put("resp_code", "failed");
			map.put("channel_type", "jfcoin");
			map.put("resp_message", "查询默认结算卡有误");
			return map;
		}
		String respcode = jsonObject.getString("resp_code");
		if (!"000000".equals(respcode)) {

			maps.put("resp_code", "failed");
			maps.put("channel_type", "jfcoin");
			maps.put("resp_message", "没有结算卡");
			return maps;
		}

		// 默认提现卡卡号
		String cardNo = resultObj.getString("cardNo");
		String phone = resultObj.getString("phone");

		JFQuickRegister jfQuickRegisterByPhoneAndBankCard;
		String merchantCode = null;
		try {
			jfQuickRegisterByPhoneAndBankCard = topupPayChannelBusiness.getJFQuickRegisterByPhoneAndBankCard(phone,
					cardNo);
			merchantCode = jfQuickRegisterByPhoneAndBankCard.getMerchantCode();
		} catch (Exception e1) {
			log.info("获取进件信息失败=====");
		}

		// 查询信用卡信息
		restTemplate = new RestTemplate();
		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/bank/default/cardno";
		requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("cardno", bankCard);
		requestEntity.add("type", "0");
		result = restTemplate.postForObject(url, requestEntity, String.class);
		log.info("接口/v1.0/user/bank/default/cardno--RESULT================" + result);
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e) {
			log.error("查询银行卡信息出错");
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", "查询银行卡信息有误");
			return map;
		}
		if (resultObj == null) {
			return null;
		}

		String userName = resultObj.getString("userName");
		/** 身份证号 */
		String idcard = resultObj.getString("idcard");
		String phone1 = resultObj.getString("phone");
		String bankName = resultObj.getString("bankName");

		if (bankName.contains("邮")) {
			bankName = "中国邮政储蓄银行";
		} else if (bankName.contains("浦")) {
			bankName = "上海浦东发展银行";
		}

		BankNumCode bankNumCodeByBankName;
		String bankNum = null;
		String bankCode = null;
		try {
			bankNumCodeByBankName = topupPayChannelBusiness.getBankNumCodeByBankName(bankName);
			bankNum = bankNumCodeByBankName.getBankNum();
			bankCode = bankNumCodeByBankName.getBankCode();
		} catch (Exception e) {
			log.info("获取银行代码代号出错啦=======" + e);
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", "暂不支持该银行，请重新更换银行");
			return map;
		}

		// 支付接口的交易代码
		String txnCode = "702001";
		String api = "/rest/api/" + txnCode;

		// 获取令牌
		String token = new PayGetToken().token(Key, TokenConstants.CONSUME_PAY_TOKEN, ordercode, partnerNo, JFurl);

		// 将订单金额变成以分为单位
		String Amount = new BigDecimal(amount).multiply(new BigDecimal("100")).setScale(0).toString();

		// 异步通知地址
		String notifyUrl = ipAddress + "/v1.0/paymentchannel/topup/shaogao/pay_notify_call";

		JSONObject dto = new JSONObject();
		dto.put("token", token);// token
		dto.put("consumeOrderId", ordercode);// 订单号
		dto.put("platMerchantCode", merchantCode);// 商户号
		dto.put("smsCode", smsCode);// 短信验证码
		dto.put("merchantRateCode", rateCode);// 费率编码
		dto.put("payAmount", Amount);// 支付金额
		dto.put("accountName", userName);// 银行卡户名
		dto.put("cardNo", bankCard);// 银行卡卡号
		dto.put("cardType", "C");// 银行卡类型
		dto.put("certType", "ID");// 证件类型
		dto.put("certNo", idcard);// 身份证号
		dto.put("phoneno", phone1);// 预留手机号
		dto.put("bankCode", bankNum);// 银行代码
		dto.put("bankAbbr", bankCode);// 银行代号
		dto.put("productName", "充值缴费");// 商品名称
		dto.put("productDesc", "充值缴费");// 商品描述
		dto.put("callBackUrl", notifyUrl);// 回调地址
		dto.put("head", this.getHead(ordercode, partnerNo, txnCode));

		// ordercode
		String execute = this.execute(Key, JFurl, api, dto.toString(), partnerNo, ordercode);
		log.info(execute);

		String res;
		// 返回状态码
		String respCode;
		String respMsg;
		try {
			com.alibaba.fastjson.JSONObject resJson = JSON.parseObject(execute);
			String sign = resJson.getString("signature");
			res = AES.decode(Base64.decode(resJson.getString("encryptData")), Key.substring(0, 16));

			jsonObject = JSONObject.fromObject(res);
			log.info("jsonObject=======" + jsonObject);
			JSONObject head = jsonObject.getJSONObject("head");
			respCode = head.getString("respCode");
			log.info("respCode=====" + respCode);
			respMsg = head.getString("respMsg");
			log.info("respMsg======" + respMsg);

			if ("000000".equals(respCode) && "success".equals(respMsg)) {
				map.put("resp_code", "success");
				map.put("channel_type", "jf");
				map.put("redirect_url", ipAddress + "/v1.0/paymentchannel/topup/sdjpaysuccess");

			} else {

				map.put("resp_code", "failed");
				map.put("channel_type", "jf");
				map.put("redirect_url", ipAddress + "/v1.0/paymentchannel/topup/sdjpayerror");
			}

		} catch (Exception e) {
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("redirect_url", ipAddress + "/v1.0/paymentchannel/topup/sdjpayerror");

		}

		return map;
	}

	// 提现接口
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/topup/jfshangao/withdraw")
	public @ResponseBody Object Withdraw(HttpServletRequest request,
			@RequestParam(value = "ordercode") String ordercode) throws Exception {
		log.info("开始进入提现接口========================");
		Map map = new HashMap();
		Map<String, String> maps = new HashMap<String, String>();
		RestTemplate restTemplate = new RestTemplate();
		URI uri = util.getServiceUrl("transactionclear", "error url request!");
		String url = uri.toString() + "/v1.0/transactionclear/payment/query/ordercode";
		MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("order_code", ordercode);
		String result = restTemplate.postForObject(url, requestEntity, String.class);
		log.info("RESULT================" + result);
		JSONObject jsonObject;
		JSONObject resultObj;
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e1) {
			log.error("查询订单信息出错");
			map.put("resp_code", "failed");
			map.put("channel_type", "jfcoin");
			map.put("resp_message", "没有该订单信息");
			return map;
		}

		String realamount = resultObj.getString("realAmount");
		String userid = resultObj.getString("userid");
		// 费率
		String rate = resultObj.getString("rate");
		// 额外费率
		String extraFee = resultObj.getString("extraFee");
		// 充值卡卡号
		String bankCard = resultObj.getString("bankcard");
		String amount = resultObj.getString("amount");

		restTemplate = new RestTemplate();
		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/bank/default/userid";
		requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("user_id", userid);
		result = restTemplate.postForObject(url, requestEntity, String.class);

		log.info("RESULT================" + result);
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e1) {
			log.error("查询默认结算卡出错");
			map.put("resp_code", "failed");
			map.put("channel_type", "jfcoin");
			map.put("resp_message", "查询默认结算卡有误");
			return map;
		}
		String respcode = jsonObject.getString("resp_code");
		if (!"000000".equals(respcode)) {

			maps.put("resp_code", "failed");
			maps.put("channel_type", "jfcoin");
			maps.put("resp_message", "没有结算卡");
			return maps;
		}

		// 默认提现卡卡号
		String cardNo = resultObj.getString("cardNo");
		String userName = resultObj.getString("userName");
		/** 身份证号 */
		String idcard = resultObj.getString("idcard");
		String phone = resultObj.getString("phone");
		String bankName = resultObj.getString("bankName");

		restTemplate = new RestTemplate();
		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/query/randomuserid";
		requestEntity = new LinkedMultiValueMap<String, String>();

		String shopUserId;
		try {
			result = restTemplate.postForObject(url, requestEntity, String.class);
			jsonObject = JSONObject.fromObject(result);
			shopUserId = jsonObject.getString("result");
		} catch (Exception e1) {
			log.error("查询用户ID出错！！！！");
			maps.put("resp_code", "failed");
			maps.put("channel_type", "sdj");
			maps.put("resp_message", "没有查询到用户ID");
			return maps;
		}

		log.info("随机获取的userId" + shopUserId);

		restTemplate = new RestTemplate();
		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/shops/query/uid";
		requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("userid", shopUserId);
		result = restTemplate.postForObject(url, requestEntity, String.class);

		log.info("RESULT================" + result);
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e1) {
			log.error("查询商铺信息出错");
			map.put("resp_code", "failed");
			map.put("channel_type", "jfcoin");
			map.put("resp_message", "查询商铺信息有误");
			return map;
		}

		String shopName = resultObj.getString("name");// 商户全称

		restTemplate = new RestTemplate();
		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/bank/default/cardno";
		requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("cardno", bankCard);
		requestEntity.add("type", "0");
		result = restTemplate.postForObject(url, requestEntity, String.class);
		log.info("接口/v1.0/user/bank/default/cardno--RESULT================" + result);
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e) {
			log.error("查询银行卡信息出错");
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", "查询银行卡信息有误");
			return map;
		}
		if (resultObj == null) {
			return null;
		}

		String cardName = resultObj.getString("bankName");

		String cardname = Util.queryBankNameByBranchName(cardName);

		// =================================

		// 获取令牌
		String token = new PayGetToken().token(Key, TokenConstants.PAY_AMOUNT_WITHDRAW_DEPOSIT_TOKEN, ordercode,
				partnerNo, JFurl);

		if ("failed".equals(token)) {
			log.info("获取token出错啦=======");
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", "获取token出错啦");
			return map;
		}

		// 提现接口的交易代码
		String txnCode = "702002";
		String api = "/rest/api/" + txnCode;

		JFQuickRegister jfQuickRegister = topupPayChannelBusiness.getJFQuickRegisterByPhoneAndBankCard(phone, cardNo);
		String province = jfQuickRegister.getProvince();
		String city = jfQuickRegister.getCity();
		String bankbranchname = jfQuickRegister.getBankbranchname();
		String merchantCode = jfQuickRegister.getMerchantCode();
		String merchantUuid = jfQuickRegister.getMerchantUuid();

		// 将额外费用变成以分为单位
		String ExtraFee = new BigDecimal(extraFee).multiply(new BigDecimal("100")).setScale(0).toString();

		if (bankName.contains("邮")) {
			bankName = "中国邮政储蓄银行";
		} else if (bankName.contains("浦")) {
			bankName = "上海浦东发展银行";
		}

		BankNumCode bankNumCodeByBankName;
		String bankNum = null;
		String bankCode = null;
		try {
			bankNumCodeByBankName = topupPayChannelBusiness.getBankNumCodeByBankName(bankName);
			bankNum = bankNumCodeByBankName.getBankNum();
			bankCode = bankNumCodeByBankName.getBankCode();
		} catch (Exception e) {
			log.info("获取银行代码代号出错啦=======" + e);
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", "获取银行代码代号出错啦");
			return map;
		}

		BankInfoCode bankInfoCodeByBankName;
		String bankNo = null;
		try {
			bankInfoCodeByBankName = topupPayChannelBusiness.getBankInfoCodeByBankName(bankbranchname);
			bankNo = bankInfoCodeByBankName.getBankNo();
		} catch (Exception e) {
			log.info("获取支行联行号出错啦=======" + e);
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", "获取支行联行号出错啦");
			return map;
		}

		BigDecimal bigamount = new BigDecimal(amount);
		BigDecimal bigrate = new BigDecimal(rate);
		BigDecimal bigextraFee = new BigDecimal(extraFee);

		// 订单总金额乘以费率的值
		BigDecimal multiply = bigamount.multiply(bigrate);
		// 订单总金额减去 订单总金额乘以费率的值
		BigDecimal subtract = bigamount.subtract(multiply);
		// 再减去额外费用
		BigDecimal Amount = subtract.subtract(bigextraFee);

		BigDecimal setScale = Amount.setScale(2, RoundingMode.CEILING);

		String SetScale = new BigDecimal(setScale + "").multiply(new BigDecimal("100")).setScale(0).toString();

		log.info("用户提现的金额====SetScale" + SetScale);

		JSONObject dto = new JSONObject();

		dto.put("token", token);// token
		dto.put("merchantUuid", merchantUuid);// 商户UUID
		dto.put("withdrawOrderId", ordercode);// 提现订单号
		dto.put("walletType", "400");// 钱包类型
		dto.put("amount", SetScale);// 提现金额
		dto.put("bankAccountName", userName);// 银行卡户名
		dto.put("bankAccountNo", cardNo);// 银行卡卡号
		dto.put("bankAccountType", "PRIVATE");// 银行账户类型
		dto.put("bankName", bankName);// 银行名称
		dto.put("bankSubName", bankbranchname);// 支行名称
		dto.put("bankChannelNo", bankNo);// 支行联行号
		dto.put("bankCode", bankNum);// 银行代码
		dto.put("bankAbbr", bankCode);// 银行代号
		dto.put("bankProvince", province);// 银行省份
		dto.put("bankCity", city);// 银行城市
		dto.put("bankArea", city);// 银行区县
		dto.put("head", this.getHead(ordercode, partnerNo, txnCode));

		String execute = this.execute(Key, JFurl, api, dto.toString(), partnerNo, ordercode);
		log.info(execute);

		String res;
		// 返回状态码
		String respCode;
		String respMsg;
		try {
			com.alibaba.fastjson.JSONObject resJson = JSON.parseObject(execute);
			String sign = resJson.getString("signature");
			res = AES.decode(Base64.decode(resJson.getString("encryptData")), Key.substring(0, 16));

			jsonObject = JSONObject.fromObject(res);
			log.info("jsonObject=======" + jsonObject);
			JSONObject head = jsonObject.getJSONObject("head");
			respCode = head.getString("respCode");
			log.info("respCode=====" + respCode);
			respMsg = head.getString("respMsg");
			log.info("respMsg======" + respMsg);

			if ("000000".equals(respCode) && "success".equals(respMsg)) {
				map.put("resp_code", "success");
				map.put("channel_type", "jf");

			} else {

				map.put("resp_code", "failed");
				map.put("channel_type", "jf");
				map.put("resp_message", respMsg);
			}

		} catch (Exception e) {
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", "亲，提现失败啦！");

		}

		return null;
	}

	// 卡开通状态查询
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/topup/jfshangao/opencardquery")
	public @ResponseBody Object OpenCardQuery(HttpServletRequest request,
			@RequestParam(value = "ordercode") String ordercode,
			@RequestParam(value = "platMerchantCode") String platMerchantCode) throws Exception {

		Map map = new HashMap();
		// 卡开通状态查询接口的交易代码
		String txnCode = "701010";
		String api = "/rest/api/" + txnCode;

		// 获取令牌
		String token = new PayGetToken().token(Key, TokenConstants.OPEN_CARD_STATUS_QUERY_TOKEN, ordercode, partnerNo,
				JFurl);

		if ("failed".equals(token)) {
			log.info("获取token出错啦=======");
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", "获取token出错啦");
			return map;
		}

		JSONObject dto = new JSONObject();
		dto.put("token", token);// token
		dto.put("smsOrderId", ordercode);// 订单号
		dto.put("platMerchantCode", platMerchantCode);// 商户号
		dto.put("head", this.getHead(ordercode, partnerNo, txnCode));

		// ordercode
		String execute = this.execute(Key, JFurl, api, dto.toString(), partnerNo, ordercode);
		log.info(execute);

		String res;
		// 返回状态码
		String respCode;
		String respMsg = null;
		try {
			com.alibaba.fastjson.JSONObject resJson = JSON.parseObject(execute);
			String sign = resJson.getString("signature");
			res = AES.decode(Base64.decode(resJson.getString("encryptData")), Key.substring(0, 16));

			JSONObject jsonObject = JSONObject.fromObject(res);
			log.info("jsonObject=======" + jsonObject);
			JSONObject head = jsonObject.getJSONObject("head");
			log.info("head=======" + head);
			respCode = head.getString("respCode");
			log.info("respCode=====" + respCode);
			respMsg = head.getString("respMsg");
			log.info("respMsg======" + respMsg);
			String activateStatus = jsonObject.getString("activateStatus");
			log.info("activateStatus======" + activateStatus);

			if ("SUCCESS".equalsIgnoreCase(activateStatus)) {

				map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
				map.put(CommonConstants.RESP_MESSAGE, "成功");
				return map;

			} else if ("SIGNING".equalsIgnoreCase(activateStatus) || "INIT".equalsIgnoreCase(activateStatus)) {

				map.put(CommonConstants.RESP_CODE, CommonConstants.WAIT_CHECK);
				map.put(CommonConstants.RESP_MESSAGE, "等待处理");
				return map;

			} else {
				map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
				map.put(CommonConstants.RESP_MESSAGE, "失败");
				return map;
			}

		} catch (Exception e) {
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", "亲，绑卡失败啦！");
			return map;
		}

	}

	// 结算卡变更接口
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/topup/jfshangao/updatecard")
	public @ResponseBody Object updateCard(HttpServletRequest request,
			@RequestParam(value = "ordercode") String ordercode,
			@RequestParam(value = "provinceOfBank") String provinceOfBank,
			@RequestParam(value = "cityOfBank") String cityOfBank,
			@RequestParam(value = "bankBranchName") String bankBranchName) throws Exception {

		Map map = new HashMap();
		Map<String, String> maps = new HashMap<String, String>();
		RestTemplate restTemplate = new RestTemplate();
		URI uri = util.getServiceUrl("transactionclear", "error url request!");
		String url = uri.toString() + "/v1.0/transactionclear/payment/query/ordercode";
		MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("order_code", ordercode);
		String result = restTemplate.postForObject(url, requestEntity, String.class);
		log.info("RESULT================" + result);
		JSONObject jsonObject = JSONObject.fromObject(result);
		JSONObject resultObj = jsonObject.getJSONObject("result");

		String userid = resultObj.getString("userid");

		restTemplate = new RestTemplate();
		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/bank/default/userid";
		requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("user_id", userid);
		result = restTemplate.postForObject(url, requestEntity, String.class);

		log.info("RESULT================" + result);
		jsonObject = JSONObject.fromObject(result);
		resultObj = jsonObject.getJSONObject("result");

		String cardNo = resultObj.getString("cardNo");
		String userName = resultObj.getString("userName");
		/** 身份证号 */
		String idcard = resultObj.getString("idcard");
		String phone = resultObj.getString("phone");
		// 开户行所在省
		log.info("provinceOfBank" + provinceOfBank);
		// 开户行所在市
		log.info("cityOfBank" + cityOfBank);
		// 银行名称
		String bankName = resultObj.getString("bankName");

		String cardType = resultObj.getString("cardType");

		// 修改进件信息接口的交易代码
		String txnCode = "701004";
		String api = "/rest/api/" + txnCode;
		
		BankNumCode bankNumCodeByBankName;
		String bankNum = null;
		String bankCode = null;
		try {
			bankNumCodeByBankName = topupPayChannelBusiness.getBankNumCodeByBankName(bankName);
			bankNum = bankNumCodeByBankName.getBankNum();
			bankCode = bankNumCodeByBankName.getBankCode();
		} catch (Exception e) {
			log.info("获取银行代码代号出错啦=======" + e);
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", "获取银行代码代号出错啦");
			return map;
		}
		
		BankInfoCode bankInfoCodeByBankName;
		String bankNo = null;
		try {
			bankInfoCodeByBankName = topupPayChannelBusiness.getBankInfoCodeByBankName(bankBranchName);
			bankNo = bankInfoCodeByBankName.getBankNo();
		} catch (Exception e) {
			log.info("获取支行联行号出错啦=======" + e);
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", "获取支行联行号出错啦");
			return map;
		}
		
		JFQuickRegister jfQuickRegister = topupPayChannelBusiness.getJFQuickRegisterByPhoneAndBankCard(phone, cardNo);
		String merchantCode = jfQuickRegister.getMerchantCode();

		// 获取令牌
		String token = new PayGetToken().token(Key, TokenConstants.MERCHANT_CHANGE_TOKEN, ordercode, partnerNo, JFurl);

		if ("failed".equals(token)) {
			log.info("获取token出错啦=======");
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", "获取token出错啦");
			return map;
		}

		JSONObject dto = new JSONObject();

		  dto.put("token", token);// token 
		  dto.put("platMerchantCode", merchantCode);//商户UUID 
		  dto.put("changeType", "2");// 银行卡信息变更 
		  dto.put("bankAccountNo", cardNo);//银行卡卡号
		  dto.put("phoneno", phone);// 预留手机号 
		  dto.put("bankName", bankName);//银行名称 
		  dto.put("bankSubName", bankBranchName);// 银行支行名称 
		  dto.put("bankCode",bankNum);// 银行代码
		  dto.put("bankAbbr", bankCode);// 银行代号
		  dto.put("bankChannelNo", bankNo);// 支行联行号 
		  dto.put("bankProvince",provinceOfBank);// 开户行省份 
		  dto.put("bankCity", cityOfBank);// 开户行城市 
		  dto.put("rateCode",rateCode);// 费率编码 
		dto.put("head", this.getHead(ordercode, partnerNo, txnCode));

		// ordercode
		String execute = this.execute(Key, JFurl, api, dto.toString(), partnerNo, ordercode);
		log.info(execute);

		String res;
		// 返回状态码
		String respCode;
		String respMsg;
		try {
			com.alibaba.fastjson.JSONObject resJson = JSON.parseObject(execute);
			String sign = resJson.getString("signature");
			res = AES.decode(Base64.decode(resJson.getString("encryptData")), Key.substring(0, 16));

			jsonObject = JSONObject.fromObject(res);
			log.info("jsonObject=======" + jsonObject);
			JSONObject head = jsonObject.getJSONObject("head");
			respCode = head.getString("respCode");
			log.info("respCode=====" + respCode);
			respMsg = head.getString("respMsg");
			log.info("respMsg======" + respMsg);

			if ("000000".equals(respCode) && "success".equals(respMsg)) {
				JFQuickRegister jfQuickRegisterByIdCard = topupPayChannelBusiness.getJFQuickRegisterByIdCard(idcard);
				jfQuickRegisterByIdCard.setBankCard(cardNo);
				
				topupPayChannelBusiness.createJFQuickRegister(jfQuickRegisterByIdCard);
				
				map.put("resp_code", "success");
				map.put("channel_type", "jf");
				map.put("redirect_url",ipAddress + "/v1.0/paymentchannel/topup/jfshangaopay?ordercode="+ordercode);
				return map;
				
			} else {

				map.put("resp_code", "failed");
				map.put("channel_type", "jf");
				map.put("resp_message", respMsg);
			}

		} catch (Exception e) {
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", "亲，绑卡失败啦！");

		}

		return null;
	}

	// 用于页面请求跳转的接口=======================================
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/topup/jfshangao/turntopage")
	public @ResponseBody Object turnToPage(HttpServletRequest request,
			@RequestParam(value = "ordercode") String ordercode) throws Exception {

		log.info("开始进入用于页面请求跳转接口========================");
		Map map = new HashMap();
		Map<String, String> maps = new HashMap<String, String>();
		RestTemplate restTemplate = new RestTemplate();
		URI uri = util.getServiceUrl("transactionclear", "error url request!");
		String url = uri.toString() + "/v1.0/transactionclear/payment/query/ordercode";
		MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("order_code", ordercode);
		String result = restTemplate.postForObject(url, requestEntity, String.class);
		log.info("RESULT================" + result);
		JSONObject jsonObject;
		JSONObject resultObj;
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e1) {
			log.error("查询订单信息出错");
			map.put("resp_code", "failed");
			map.put("channel_type", "jfcoin");
			map.put("resp_message", "没有该订单信息");
			return map;
		}

		String userid = resultObj.getString("userid");
		// 充值卡卡号
		String bankCard = resultObj.getString("bankcard");

		// 查询信用卡信息
		restTemplate = new RestTemplate();
		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/bank/default/cardno";
		requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("cardno", bankCard);
		requestEntity.add("type", "0");
		result = restTemplate.postForObject(url, requestEntity, String.class);
		log.info("接口/v1.0/user/bank/default/cardno--RESULT================" + result);
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e) {
			log.error("查询银行卡信息出错");
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", "查询银行卡信息有误");
			return map;
		}
		if (resultObj == null) {
			return null;
		}

		String cardName = resultObj.getString("bankName");
		String expiredTime = resultObj.getString("expiredTime");

		String securityCode = resultObj.getString("securityCode");

		String cardtype = resultObj.getString("cardType");

		String cardname = Util.queryBankNameByBranchName(cardName);

		map.put("resp_code", "success");
		map.put("channel_type", "jf");
		map.put("redirect_url",
				ipAddress + "/v1.0/paymentchannel/topup/tojfshangaobindcard?bankName="
						+ URLEncoder.encode(cardname, "UTF-8") + "&cardType=" + URLEncoder.encode(cardtype, "UTF-8")
						+ "&bankCard=" + bankCard + "&ordercode=" + ordercode + "&expiredTime=" + expiredTime
						+ "&securityCode=" + securityCode);
		return map;

	}

	// ========================

	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/topup/jfshangao/turntopaypage")
	public @ResponseBody Object turnToCJPayPage(HttpServletRequest request,
			@RequestParam(value = "ordercode") String ordercode) throws Exception {

		Map map = new HashMap();

		map.put("resp_code", "success");
		map.put("channel_type", "jf");
		map.put("redirect_url", ipAddress + "/v1.0/paymentchannel/topup/jfshangaopay?&ordercode=" + ordercode);
		return map;

	}

	// 中转接口
	@RequestMapping(method = RequestMethod.GET, value = "/v1.0/paymentchannel/topup/jfshangaopay")
	public String returnjfapipay(HttpServletRequest request, HttpServletResponse response, Model model)
			throws IOException {
		// 设置编码
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");

		String ordercode = request.getParameter("ordercode");

		model.addAttribute("ordercode", ordercode);

		return "jfshangaopaymessage";
	}

	// 跳转确认提现卡页面的中转接口
	@RequestMapping(method = RequestMethod.GET, value = "/v1.0/paymentchannel/topup/tojfshangaobankinfo")
	public String tojfshangaobankinfo(HttpServletRequest request, HttpServletResponse response, Model model)
			throws IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		log.info("/v1.0/paymentchannel/topup/tojfcoinbankinfo=========tojfcoinbankinfo");
		String bankName = request.getParameter("bankName");// 结算卡银行名称
		String bankNo = request.getParameter("bankNo");// 结算卡卡号
		String amount = request.getParameter("amount");
		String ordercode = request.getParameter("ordercode");
		String provinceOfBank = request.getParameter("provinceOfBank");
		String cityOfBank = request.getParameter("cityOfBank");
		String bankBranchName = request.getParameter("bankBranchName");
		String bankBranchId = request.getParameter("bankBranchId");
		String cardType = request.getParameter("cardType");// 结算卡的卡类型
		String isRegister = request.getParameter("isRegister");
		String cardtype = request.getParameter("cardtype");// 信用卡的卡类型
		String bankCard = request.getParameter("bankCard");// 充值卡卡号
		String cardName = request.getParameter("cardName");// 充值卡银行名称
		String expiredTime = request.getParameter("expiredTime");
		String securityCode = request.getParameter("securityCode");

		model.addAttribute("bankName", bankName);
		model.addAttribute("bankNo", bankNo);
		model.addAttribute("amount", amount);
		model.addAttribute("ordercode", ordercode);
		model.addAttribute("provinceOfBank", provinceOfBank);
		model.addAttribute("cityOfBank", cityOfBank);
		model.addAttribute("bankBranchName", bankBranchName);
		model.addAttribute("bankBranchId", bankBranchId);
		model.addAttribute("cardType", cardType);
		model.addAttribute("isRegister", isRegister);
		model.addAttribute("cardtype", cardtype);
		model.addAttribute("bankCard", bankCard);
		model.addAttribute("cardName", cardName);
		model.addAttribute("expiredTime", expiredTime);
		model.addAttribute("securityCode", securityCode);

		return "jfshangaobankInfo";
	}

	// 跳转确认绑信用卡页面的中转接口
	@RequestMapping(method = RequestMethod.GET, value = "/v1.0/paymentchannel/topup/tojfshangaobindcard")
	public String tocjbindcard(HttpServletRequest request, HttpServletResponse response, Model model)
			throws IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		log.info("/v1.0/paymentchannel/topup/tocjbindcard=========tocjbindcard");
		String cardname = request.getParameter("bankName");// 信用卡银行名称
		String ordercode = request.getParameter("ordercode");
		String cardType = request.getParameter("cardType");
		// String isRegister = request.getParameter("isRegister");
		String bankCard = request.getParameter("bankCard");// 充值卡卡号
		String expiredTime = request.getParameter("expiredTime");// 充值卡卡号
		String securityCode = request.getParameter("securityCode");// 充值卡卡号

		model.addAttribute("bankName", cardname);
		model.addAttribute("ordercode", ordercode);
		model.addAttribute("cardType", cardType);
		// model.addAttribute("isRegister", isRegister);
		model.addAttribute("bankCard", bankCard);
		model.addAttribute("expiredTime", expiredTime);
		model.addAttribute("securityCode", securityCode);

		return "jfshangaobindcard";
	}

	// 支付接口异步通知
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/topup/shaogao/pay_notify_call")
	public void paynotifyCall(HttpServletRequest request, HttpServletResponse response,
			@RequestParam String encryptData, @RequestParam String signature

	) throws Exception {

		log.info("异步回调进来了");
		String dataPlain = AES.decode(Base64.decode(encryptData), Key.substring(0, 16));
		log.info("消费回调：dataPlain: {} ", dataPlain);
		String checkSign = DigestUtils.sha1Hex(encryptData + Key.substring(16));

		log.info("消费回调：checkSign: {} ", checkSign);

		if (!Objects.equal(signature, checkSign)) {
			log.error("签名验证失败");
		}

		com.alibaba.fastjson.JSONObject parseObject = JSON.parseObject(dataPlain);
		log.info("parseObject===========" + parseObject);

		com.alibaba.fastjson.JSONObject jsonObject2 = parseObject.getJSONObject("head");

		String workId = jsonObject2.getString("workId");
		log.info("workId======" + workId);
		String respCode = jsonObject2.getString("respCode");
		log.info("respCode======" + respCode);
		String respMsg = jsonObject2.getString("respMsg");
		log.info("respMsg======" + respMsg);
		String orderId = jsonObject2.getString("orderId");
		log.info("orderId======" + orderId);

		try {
			Log.setLogFlag(true);
			Log.println("---交易： 订单结果异步通知-------------------------");

			log.info("交易： 订单结果异步通知===================");
			if ("success".equals(respMsg) && "000000".equals(respCode)) { // 订单已支付;

				// 1、检查Amount和商户系统的订单金额是否一致
				// 2、订单支付成功的业务逻辑处理请在本处增加（订单通知可能存在多次通知的情况，需要做多次通知的兼容处理）；
				// 3、返回响应内容

				synchronized (this) {
					// **更新订单状态*//*
					// **调用下单，需要得到用户的订单信息*//*
					RestTemplate restTemplate = new RestTemplate();

					URI uri = util.getServiceUrl("transactionclear", "error url request!");
					String url = uri.toString() + "/v1.0/transactionclear/payment/update";

					// **根据的用户手机号码查询用户的基本信息*//*
					MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
					requestEntity.add("status", "1");
					requestEntity.add("third_code", workId);
					requestEntity.add("order_code", orderId);
					String result = restTemplate.postForObject(url, requestEntity, String.class);

					log.info("订单状态修改成功===================");

					// **判断是否有外放的通道的处理， 如果有那么继续回调外放哦*//*
					/*
					 * uri = util.getServiceUrl("transactionclear", "error url request!"); url =
					 * uri.toString() + "/v1.0/transactionclear/payment/query/ordercode";
					 * 
					 * requestEntity = new LinkedMultiValueMap<String, String>();
					 * requestEntity.add("order_code", orderId); result =
					 * restTemplate.postForObject(url, requestEntity, String.class);
					 * 
					 * JSONObject jsonObject = JSONObject.fromObject(result); JSONObject resultObj =
					 * jsonObject.getJSONObject("result"); String outMerOrdercode =
					 * resultObj.getString("outMerOrdercode"); String orderdesc =
					 * resultObj.getString("desc"); String phone = resultObj.getString("phone");
					 * String tranamount = resultObj.getString("amount"); String channelTag =
					 * resultObj.getString("channelTag"); String notifyURL =
					 * resultObj.getString("outNotifyUrl"); if (outMerOrdercode != null &&
					 * !outMerOrdercode.equalsIgnoreCase("")) { uri = util.getServiceUrl("channel",
					 * "error url request!"); url = uri.toString() +
					 * "/v1.0/channel/callback/yilian/notify_call"; requestEntity = new
					 * LinkedMultiValueMap<String, String>(); requestEntity.add("merchant_no",
					 * phone); requestEntity.add("amount", tranamount);
					 * requestEntity.add("channel_tag", channelTag); requestEntity.add("order_desc",
					 * URLEncoder.encode(orderdesc, "UTF-8")); requestEntity.add("order_code",
					 * outMerOrdercode); requestEntity.add("sys_order", orderId);
					 * requestEntity.add("notify_url", URLEncoder.encode(notifyURL, "UTF-8"));
					 * result = restTemplate.postForObject(url, requestEntity, String.class); }
					 */

					log.info("订单已支付!");
					response.getWriter().write("000000");
				}
			} else {
				// 1、订单支付失败的业务逻辑处理请在本处增加（订单通知可能存在多次通知的情况，需要做多次通知的兼容处理，避免成功后又修改为失败）；
				// 2、返回响应内容

				log.info("订单支付失败!");
			}
		} catch (Exception e) {
			log.error(e.getMessage());
		}
		log.info("-----处理完成----");
	}

	// 银联绑卡同步通知
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/topup/jfshangao/return_call")
	public String cjReturnCallback(HttpServletRequest request, HttpServletResponse response) throws Exception {

		Map map = new HashMap();
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");

		log.info("银联绑卡同步通知进来了");

		return "cjbindcardsuccess";

	}

	// 银联绑卡异步通知
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/topup/jfshangao/notify_call")
	public void jfshangaoNotifyCallback(HttpServletRequest request, HttpServletResponse response,
			@RequestParam String encryptData, @RequestParam String signature) throws Exception {

		log.info("银联绑卡异步通知进来了");

		String dataPlain = AES.decode(Base64.decode(encryptData), Key.substring(0, 16));
		log.info("消费回调：dataPlain: {} ", dataPlain);
		String checkSign = DigestUtils.sha1Hex(encryptData + Key.substring(16));

		log.info("消费回调：checkSign: {} ", checkSign);

		if (!Objects.equal(signature, checkSign)) {
			log.error("签名验证失败");
		}

		com.alibaba.fastjson.JSONObject parseObject = JSON.parseObject(dataPlain);
		log.info("parseObject===========" + parseObject);

		com.alibaba.fastjson.JSONObject jsonObject2 = parseObject.getJSONObject("head");
		log.info("jsonObject2===========" + jsonObject2);

		String respCode = jsonObject2.getString("respCode");
		log.info("respCode======" + respCode);

		String respMsg = jsonObject2.getString("respMsg");
		log.info("respMsg======" + respMsg);

		String orderId = jsonObject2.getString("orderId");
		log.info("orderId======" + orderId);

		if ("000000".equals(respCode)) {
			String activateStatus = parseObject.getString("activateStatus");
			log.info("activateStatus======" + activateStatus);

			if ("SUCCESS".equalsIgnoreCase(activateStatus)) {

				Map map = new HashMap();
				Map<String, String> maps = new HashMap<String, String>();
				RestTemplate restTemplate = new RestTemplate();
				URI uri = util.getServiceUrl("transactionclear", "error url request!");
				String url = uri.toString() + "/v1.0/transactionclear/payment/query/ordercode";
				MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
				requestEntity.add("order_code", orderId);
				String result = restTemplate.postForObject(url, requestEntity, String.class);
				log.info("RESULT================" + result);
				JSONObject jsonObject = JSONObject.fromObject(result);
				;
				JSONObject resultObj = jsonObject.getJSONObject("result");

				String userid = resultObj.getString("userid");
				// 充值卡卡号
				String bankCard = resultObj.getString("bankcard");
				String phone = resultObj.getString("phone");

				// 查询信用卡信息
				restTemplate = new RestTemplate();
				uri = util.getServiceUrl("user", "error url request!");
				url = uri.toString() + "/v1.0/user/bank/default/cardno";
				requestEntity = new LinkedMultiValueMap<String, String>();
				requestEntity.add("cardno", bankCard);
				requestEntity.add("type", "0");
				result = restTemplate.postForObject(url, requestEntity, String.class);
				log.info("接口/v1.0/user/bank/default/cardno--RESULT================" + result);
				try {
					jsonObject = JSONObject.fromObject(result);
					resultObj = jsonObject.getJSONObject("result");
				} catch (Exception e) {
					log.error("查询银行卡信息出错");
				}

				String userName1 = resultObj.getString("userName");
				/** 身份证号 */
				String idcard1 = resultObj.getString("idcard");
				String phone1 = resultObj.getString("phone");
				String bankName1 = resultObj.getString("bankName");

				JFshangaoBindCard jfshangaoBindCard = topupPayChannelBusiness.getJFshangaoBindCard(phone, bankCard);

				if (null == jfshangaoBindCard) {
					JFshangaoBindCard jFshangaoBindCard2 = new JFshangaoBindCard();
					jFshangaoBindCard2.setPhone(phone1);
					jFshangaoBindCard2.setIdCard(idcard1);
					jFshangaoBindCard2.setBankCard(bankCard);

					try {
						topupPayChannelBusiness.createJFshangaoBindCard(jFshangaoBindCard2);
					} catch (Exception e) {

					}
				} else {
					jfshangaoBindCard.setPhone(phone1);
					jfshangaoBindCard.setIdCard(idcard1);
					jfshangaoBindCard.setBankCard(bankCard);

					try {
						topupPayChannelBusiness.createJFshangaoBindCard(jfshangaoBindCard);
					} catch (Exception e) {

					}
				}

				log.info("用户绑卡成功并存入数据库");

				PrintWriter writer = response.getWriter();
				writer.print("000000");
				writer.close();

			}

		}

	}

	// ============================================

	protected String execute(String key, String url, String api, String dataJson, String partnerNo, String orderId) {

		System.out.println("============ 请求报文:" + dataJson);
		String signKey = key.substring(16);
		String dataKey = key.substring(0, 16);
		String sign = DigestUtils.sha1Hex(dataJson + signKey);

		Map<String, String> params = Maps.newHashMap();
		params.put("encryptData", Base64.encode(AES.encode(dataJson, dataKey)));
		params.put("signData", sign);
		params.put("orderId", orderId);
		params.put("partnerNo", partnerNo);
		params.put("ext", "to be or not to be");

		System.out.println("encryptData : " + params.get("encryptData"));
		System.out.println("sign : " + params.get("sign"));
		System.out.println("partnerNo : " + params.get("partnerNo"));

		System.out.println("============ 请求地址:" + url + api);
		try {
			byte[] resByte = HttpClient4Util.getInstance().doPost(url + api, null, params);
			String resStr = new String(resByte, UTF_8);
			System.out.println("============ 返回报文原文:" + resStr);

			return resStr;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public Object getHead(String ordercode, String partnerNo, String txnCode) {
		JSONObject head = new JSONObject();
		head.put("version", "1.0.0");
		head.put("charset", "UTF-8");
		head.put("partnerNo", partnerNo); // 合作方标识号
		head.put("txnCode", txnCode); // 交易代码
		head.put("orderId", ordercode); // 订单号
		head.put("reqDate", DateTime.now().toString("yyyyMMdd"));
		head.put("reqTime", DateTime.now().toString("yyyyMMddHHmmss"));
		return head;
	}

}